from django.shortcuts import render
from rest_framework.mixins import CreateModelMixin
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.decorators import action
from . import serializers,models
from luffyapi.utils.response import APIResponse
import re
from luffyapi.libs.al_sms.send import get_code,send_message
from django.core.cache import cache
from django.conf import settings
from .throttlings import SMSThrotting

# Create your views here.


class LoginView(ViewSet):
    #登入
    @action(methods=['POST'], detail=False)
    def login(self,request,*args,**kwargs):
        ret = request.data.get('telephone')
        if ret:
            ser = serializers.CodeUserSerilaizer(data=request.data)
        else:
            ser = serializers.UserSerilaizer(data=request.data)
        if ser.is_valid():
            token = ser.context['token']
            username = ser.context['user'].username
            return APIResponse(token=token,username=username)
        else:
            return APIResponse(code=0,msg=ser.errors)

    # 手机验证码登入
    # @action(methods=['POST'], detail=False)
    # def code_login(self,request,*args,**kwargs):
    #     ser = serializers.CodeUserSerilaizer(data=request.data)
    #     if ser.is_valid():
    #         token = ser.context['token']
    #         username = ser.context['user'].username
    #         return APIResponse(token=token, username=username)
    #     else:
    #         return APIResponse(code=0, msg=ser.errors)


    # 检测手机号是否合法



    @action(detail=False)
    def check_telephone(self, request, *args, **kwargs):
        telephone = request.query_params.get('telephone')
        if not re.match('^1[3-9][0-9]{9}', telephone):
            return APIResponse(code=0, msg='手机号不合法')
        try:
            models.User.objects.get(telephone=telephone)
            return APIResponse(code=1)
        except:
            return APIResponse(code=0, msg='手机号不存在')


    # 手机发送验证码
    @action(methods=['GET'], detail=False,throttle_classes=(SMSThrotting,))
    def send(self, request, *args, **kwargs):
        telephone = request.query_params.get('telephone')
        if not re.match('^1[3-9][0-9]{9}', telephone):
            return APIResponse(code=0, msg='手机号不合法')
        code = get_code()
        # result = send_message(telephone, code)
        result = True
        # 验证码保存（保存到哪？）
        # sms_cache_%s
        cache.set(settings.PHONE_CACHE_KEY % telephone, code, 180)
        if result:
            return APIResponse(code=1, msg='验证码发送成功')
        else:
            return APIResponse(code=0, msg='验证码发送失败')



class RegisterView(GenericViewSet,CreateModelMixin):
    queryset = models.User.objects.all()
    serializer_class = serializers.UserRegisterSerilaizer
    def create(self, request, *args, **kwargs):
        response=super().create(request, *args, **kwargs)
        username=response.data.get('username')
        return APIResponse(code=1,msg='注册成功',username=username)


